// 个人中心页面专用脚本
document.addEventListener('DOMContentLoaded', function() {
    // 初始化收藏/足迹标签切换
    initFavoritesTabs();
    
    // 初始化头像编辑功能
    initAvatarEdit();
    
    // 初始化设置项点击事件
    initSettingsItems();
    
    // 初始化申请按钮功能
    initApplyButtons();
    
    // 初始化评价按钮功能
    initReviewButtons();
    
    // 初始化Tab栏切换功能
    initTabBar();
    
    // 初始化数据概览点击事件
    initDataItems();
    
    // 初始化职业评估互动功能
    initCareerAssessment();
    
    // 初始化求职进度互动功能
    initJobProgress();
    
    // 初始化课程学习互动功能
    initLearningCourses();
    
    // 初始化日程预约功能
    initRescheduleButtons();
    
    // 初始化收藏按钮
    initFavoriteButtons();
    
    // 处理图片加载错误
    handleImageErrors();
});

// 收藏/足迹标签切换
function initFavoritesTabs() {
    const tabs = document.querySelectorAll('.favorites .tab');
    const favoritesContainer = document.querySelector('.favorites-container');
    
    // 足迹数据（实际项目中应从服务器获取）
    const footprintData = [
        {
            logo: '../img/company-logo3.jpg',
            title: '后端开发实习生',
            company: '腾讯',
            salary: '7k-9k/月',
            location: '深圳'
        },
        {
            logo: '../img/company-logo1.jpg',
            title: '前端开发实习生',
            company: '字节跳动',
            salary: '6k-8k/月',
            location: '北京'
        },
        {
            logo: '../img/university-logo1.jpg',
            title: '清华大学',
            company: '高校',
            salary: '',
            location: '北京'
        },
        {
            logo: '../img/agent1.jpg',
            title: '张明 - 前BAT高级HR',
            company: '经纪人',
            salary: '',
            location: ''
        }
    ];
    
    // 收藏数据（当前页面已有HTML结构）
    
    if (tabs.length > 0 && favoritesContainer) {
        tabs.forEach((tab, index) => {
            tab.addEventListener('click', function() {
                // 获取关联的标签页ID
                const tabId = this.getAttribute('data-tab');
                
                // 移除所有标签的active类
                tabs.forEach(t => t.classList.remove('active'));
                // 为当前点击的标签添加active类
                this.classList.add('active');
                
                // 隐藏所有内容面板
                const tabPanes = document.querySelectorAll('.tab-pane');
                tabPanes.forEach(pane => pane.classList.remove('active'));
                
                // 显示与当前标签关联的内容面板
                const activePane = document.getElementById(tabId);
                if (activePane) {
                    activePane.classList.add('active');
                    
                    // 如果是足迹标签页，初始化收藏按钮
                    if (tabId === 'history-tab') {
                        initFavoriteButtons();
                    }
                }
                
                // 处理新加载的图片
                handleImageErrors();
            });
        });
    }
}

// 获取原始收藏HTML
function getOriginalFavoritesHTML() {
    return `
        <div class="favorites-item">
            <img src="../img/company-logo1.jpg" alt="企业Logo" class="company-logo">
            <div class="job-info">
                <h3>前端开发实习生</h3>
                <p class="company">字节跳动</p>
                <div class="job-details">
                    <span class="salary">6k-8k/月</span>
                    <span class="location">北京</span>
                </div>
            </div>
            <button class="apply-btn">申请</button>
        </div>
        <div class="favorites-item">
            <img src="../img/company-logo2.jpg" alt="企业Logo" class="company-logo">
            <div class="job-info">
                <h3>产品经理实习生</h3>
                <p class="company">阿里巴巴</p>
                <div class="job-details">
                    <span class="salary">5k-7k/月</span>
                    <span class="location">杭州</span>
                </div>
            </div>
            <button class="apply-btn">申请</button>
        </div>
        <div class="favorites-item">
            <img src="../img/company-logo3.jpg" alt="企业Logo" class="company-logo">
            <div class="job-info">
                <h3>后端开发实习生</h3>
                <p class="company">腾讯</p>
                <div class="job-details">
                    <span class="salary">7k-9k/月</span>
                    <span class="location">深圳</span>
                </div>
            </div>
            <button class="apply-btn">申请</button>
        </div>
    `;
}

// 显示足迹内容
function showFootprints(footprints) {
    const favoritesContainer = document.querySelector('.favorites-container');
    
    if (favoritesContainer) {
        let html = '';
        
        footprints.forEach(item => {
            html += `
                <div class="favorites-item">
                    <img src="${item.logo}" alt="${item.title}" class="company-logo">
                    <div class="job-info">
                        <h3>${item.title}</h3>
                        <p class="company">${item.company}</p>
                        <div class="job-details">
                            ${item.salary ? `<span class="salary">${item.salary}</span>` : ''}
                            ${item.location ? `<span class="location">${item.location}</span>` : ''}
                        </div>
                    </div>
                    <div class="view-time">浏览于 今天</div>
                </div>
            `;
        });
        
        favoritesContainer.innerHTML = html;
    }
}

// 头像编辑功能
function initAvatarEdit() {
    const editAvatarBtn = document.querySelector('.edit-avatar');
    
    if (editAvatarBtn) {
        editAvatarBtn.addEventListener('click', function() {
            // 实际项目中应打开文件选择对话框
            alert('头像上传功能正在开发中，敬请期待！');
        });
    }
}

// 设置项点击事件
function initSettingsItems() {
    const settingsItems = document.querySelectorAll('.settings-item');
    
    settingsItems.forEach(item => {
        item.addEventListener('click', function() {
            const settingName = this.querySelector('span').textContent;
            alert(`${settingName}功能正在开发中，敬请期待！`);
        });
    });
}

// 申请按钮功能
function initApplyButtons() {
    const applyButtons = document.querySelectorAll('.apply-btn');
    
    applyButtons.forEach(button => {
        button.addEventListener('click', function() {
            const jobTitle = this.closest('.favorites-item').querySelector('h3').textContent;
            const company = this.closest('.favorites-item').querySelector('.company').textContent;
            
            // 显示申请确认对话框
            if (confirm(`确定要申请 ${company} 的 ${jobTitle} 职位吗？`)) {
                // 模拟申请成功
                this.textContent = '已申请';
                this.disabled = true;
                this.style.backgroundColor = '#999';
                
                // 显示成功提示
                showToast('申请成功，请等待企业反馈');
                
                // 实际项目中这里会发送申请请求到服务器
                console.log('申请职位:', {公司: company, 职位: jobTitle});
            }
        });
    });
}

// 评价按钮功能
function initReviewButtons() {
    const reviewButtons = document.querySelectorAll('.review-btn');
    
    reviewButtons.forEach(button => {
        button.addEventListener('click', function() {
            const agentName = this.closest('.consulting-item').querySelector('h3').textContent;
            const serviceName = this.closest('.consulting-item').querySelector('.service').textContent.replace('服务项目：', '');
            
            // 弹出评分对话框（实际项目中应使用更友好的UI）
            const score = prompt(`请为${agentName}的${serviceName}服务评分（1-5分）:`, '5');
            
            if (score) {
                const comment = prompt('请输入评价内容（可选）:');
                
                // 模拟评价成功
                this.textContent = '已评价';
                this.disabled = true;
                this.style.backgroundColor = '#ddd';
                
                // 显示成功提示
                showToast('评价成功，感谢您的反馈');
                
                // 实际项目中这里会发送评价请求到服务器
                console.log('提交评价:', {
                    经纪人: agentName, 
                    服务: serviceName,
                    评分: score,
                    评价内容: comment
                });
            }
        });
    });
}

// Tab栏切换功能
function initTabBar() {
    const tabItems = document.querySelectorAll('.tab-bar .tab-item');
    
    tabItems.forEach((tab, index) => {
        tab.addEventListener('click', function() {
            // 获取目标页面
            const targetPage = this.getAttribute('data-page');
            
            // 如果当前不在目标页面，则跳转
            if (!this.classList.contains('active')) {
                switch(targetPage) {
                    case 'index':
                        window.location.href = '../index.html';
                        break;
                    case 'discovery':
                        window.location.href = 'discover.html';
                        break;
                    case 'agents':
                        window.location.href = 'agents.html';
                        break;
                    case 'profile':
                        // 已经在个人中心页面，不需要跳转
                        break;
                }
            }
        });
    });
}

// 显示提示消息
function showToast(message) {
    // 创建提示框元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    
    // 设置提示框样式
    toast.style.position = 'fixed';
    toast.style.top = '60px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.padding = '8px 16px';
    toast.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    toast.style.color = '#fff';
    toast.style.borderRadius = '4px';
    toast.style.zIndex = '1000';
    toast.style.opacity = '0';
    toast.style.transition = 'opacity 0.3s ease';
    
    // 将提示框添加到body
    document.body.appendChild(toast);
    
    // 显示提示框
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 2秒后隐藏并移除提示框
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}

// 处理图片加载错误
function handleImageErrors() {
    // 首先检查是否已定义了预加载图片集合(在main.js中)
    if (typeof preloadedImages === 'undefined') {
        // 如果未定义，创建自己的版本
        window.preloadedImages = {
            agents: [
                'https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1607746882042-944635dfe10e?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1573497019940-1c28c88b4f3e?w=300&h=300&auto=format&fit=crop'
            ],
            avatars: [
                'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1599566150163-29194dcaad36?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1527980965255-d3b416303d12?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1570295999919-56ceb5ecca61?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1633332755192-727a05c4013d?w=300&h=300&auto=format&fit=crop'
            ],
            activities: [
                'https://images.unsplash.com/photo-1540317580384-e5d43867caa6?w=600&h=400&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1588702547923-7093a6c3ba33?w=600&h=400&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1573164574511-73c773193279?w=600&h=400&auto=format&fit=crop'
            ],
            logos: [
                'https://images.unsplash.com/photo-1560179707-f14e90ef3623?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1611162617213-7d7a39e9b1d7?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1599305445671-ac291c95aaa9?w=300&h=300&auto=format&fit=crop',
                'https://images.unsplash.com/photo-1581287053822-fd7bf4f4bfec?w=300&h=300&auto=format&fit=crop'
            ]
        };
    }
    
    // 为所有图片添加加载错误处理
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        // 避免重复添加事件
        if (img.dataset.errorHandled) {
            return;
        }
        img.dataset.errorHandled = 'true';
        
        img.addEventListener('error', function() {
            // 根据图片尺寸设置占位符
            const width = this.width || this.getAttribute('width') || 300;
            const height = this.height || this.getAttribute('height') || 300;
            
            // 获取图片类别（根据类名或父元素判断）
            let category = '';
            
            // 基于类名或父元素确定图片类别
            if (this.classList.contains('avatar') || this.parentElement.classList.contains('avatar-container')) {
                category = 'avatars';
            } else if (this.classList.contains('company-logo') || this.closest('.company-logo') || this.closest('.favorites-item')) {
                category = 'logos';
            } else if (this.classList.contains('agent-avatar') || this.closest('.agent-info')) {
                category = 'agents';
            } else if (this.classList.contains('activity-img') || this.closest('.activity-info')) {
                category = 'activities';
            }
            
            // 选择适当的图片
            let imageSrc;
            if (preloadedImages[category]) {
                const randomIndex = Math.floor(Math.random() * preloadedImages[category].length);
                imageSrc = preloadedImages[category][randomIndex];
            } else {
                // 默认图片
                imageSrc = `https://images.unsplash.com/photo-1504805572947-34fad45aed93?w=${width}&h=${height}&auto=format&fit=crop`;
            }
            
            // 设置图片源
            this.src = imageSrc;
            
            // 添加样式
            if (category === 'avatars' || category === 'agents') {
                this.style.objectFit = 'cover';
                this.style.borderRadius = '50%';
            } else {
                this.style.objectFit = 'cover';
            }
            
            // 优化加载
            this.setAttribute('loading', 'eager');
            this.style.backgroundColor = '#f0f0f0';
        });
    });
    
    // 强制触发一次所有图片的加载检查
    setTimeout(() => {
        images.forEach(img => {
            // 检查图片是否已经加载成功
            if (img.complete && img.naturalWidth > 0) {
                return; // 图片已加载成功，不需处理
            }
            
            // 清除src然后重新设置，强制触发加载事件
            const originalSrc = img.src;
            if (originalSrc) {
                img.src = '';
                img.src = originalSrc;
            } else {
                img.dispatchEvent(new Event('error'));
            }
        });
    }, 100);
}

// 数据概览点击事件
function initDataItems() {
    const dataItems = document.querySelectorAll('.data-overview .data-item');
    
    dataItems.forEach(item => {
        item.addEventListener('click', function() {
            const id = this.id;
            const sections = {
                'activities': '.registration-list',
                'favorites': '.favorites',
                'consultations': '.consulting',
                'footprints': '.favorites'
            };
            
            if (sections[id]) {
                const targetSection = document.querySelector(sections[id]);
                if (targetSection) {
                    // 滚动到对应区域
                    targetSection.scrollIntoView({ behavior: 'smooth' });
                    
                    // 如果是点击足迹，切换到足迹标签
                    if (id === 'footprints') {
                        const footprintTab = document.querySelector('.favorites .tab[data-tab="history-tab"]');
                        if (footprintTab && !footprintTab.classList.contains('active')) {
                            footprintTab.click();
                        }
                    }
                    
                    // 添加高亮效果
                    targetSection.classList.add('highlight');
                    setTimeout(() => {
                        targetSection.classList.remove('highlight');
                    }, 1500);
                }
            }
        });
    });
}

// 职业评估互动功能
function initCareerAssessment() {
    const radarChart = document.querySelector('.radar-img');
    const skillItems = document.querySelectorAll('.skill-item');
    
    if (radarChart) {
        radarChart.addEventListener('click', function() {
            showToast('正在加载详细的能力评估报告...');
            
            // 模拟加载完成后跳转
            setTimeout(() => {
                console.log('应跳转到完整的职业评估报告页面');
                // window.location.href = 'career-assessment.html';
            }, 1500);
        });
    }
    
    skillItems.forEach(item => {
        item.addEventListener('click', function() {
            const skillName = this.querySelector('.skill-name').textContent;
            const score = this.querySelector('.skill-score').textContent;
            
            showToast(`${skillName}评分：${score}，点击查看提升建议`);
        });
    });
}

// 求职进度互动功能
function initJobProgress() {
    const progressItems = document.querySelectorAll('.progress-item');
    const steps = document.querySelectorAll('.step');
    
    progressItems.forEach(item => {
        item.addEventListener('click', function() {
            const jobTitle = this.querySelector('h3').textContent;
            showToast(`正在加载"${jobTitle}"的详细申请进度...`);
        });
    });
    
    steps.forEach(step => {
        step.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止冒泡到progress-item
            
            const stepName = this.querySelector('span').textContent;
            const isCurrent = this.classList.contains('current');
            const isCompleted = this.classList.contains('completed');
            
            if (isCurrent) {
                showToast(`您当前正在"${stepName}"阶段，请关注邮件通知`);
            } else if (isCompleted) {
                showToast(`您已完成"${stepName}"阶段`);
            } else {
                showToast(`"${stepName}"阶段尚未开始`);
            }
        });
    });
}

// 课程学习互动功能
function initLearningCourses() {
    const courseItems = document.querySelectorAll('.course-item');
    
    courseItems.forEach(item => {
        item.addEventListener('click', function() {
            const courseTitle = this.querySelector('h3').textContent;
            const progress = this.querySelector('.progress-overlay').textContent;
            
            showToast(`正在进入课程：${courseTitle}，当前进度${progress}`);
            
            // 实际应用中这里应该跳转到课程详情页
            console.log('应跳转到课程详情页');
            // window.location.href = 'course-details.html?title=' + encodeURIComponent(courseTitle);
        });
    });
}

// 日程预约功能
function initRescheduleButtons() {
    const rescheduleButtons = document.querySelectorAll('.reschedule-btn');
    
    rescheduleButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation(); // 防止冒泡
            
            const agentName = this.closest('.consulting-item').querySelector('h3').textContent;
            const time = this.closest('.consulting-status').querySelector('.time').textContent;
            
            // 在实际应用中，这里应该弹出日期选择器
            const newTime = prompt(`请为与${agentName}的咨询选择新的时间（当前：${time}）：`, '04-20 14:30');
            
            if (newTime) {
                this.closest('.consulting-status').querySelector('.time').textContent = newTime;
                showToast('咨询时间已成功调整');
                
                // 实际项目中这里会发送预约修改请求到服务器
                console.log('修改预约时间:', {
                    顾问: agentName, 
                    原时间: time,
                    新时间: newTime
                });
            }
        });
    });
}

// 收藏按钮功能
function initFavoriteButtons() {
    const favoriteButtons = document.querySelectorAll('.favorite-btn');
    
    favoriteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.stopPropagation(); // 防止冒泡
            
            const jobTitle = this.closest('.history-item').querySelector('h3').textContent;
            const company = this.closest('.history-item').querySelector('.company').textContent;
            
            // 切换收藏状态
            const isFavorited = this.classList.toggle('favorited');
            if (isFavorited) {
                this.innerHTML = '<i class="bi bi-star-fill"></i>';
                this.style.color = '#ffc107';
                showToast(`已收藏"${company}"的"${jobTitle}"`);
            } else {
                this.innerHTML = '<i class="bi bi-star"></i>';
                this.style.color = 'var(--gray-color)';
                showToast(`已取消收藏"${company}"的"${jobTitle}"`);
            }
            
            // 实际项目中这里会发送收藏状态变更请求到服务器
            console.log('收藏状态变更:', {
                公司: company, 
                职位: jobTitle,
                状态: isFavorited ? '已收藏' : '已取消收藏'
            });
        });
    });
} 